package com.project.nemesis; 


import java.io.IOException;
import java.util.Iterator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;


public class DownloadFile extends HttpServlet {

	 public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {  
		  try {
			  
			  String fileName = req.getParameter("fileName");
			  
			  res.setContentType("application/force-download");
			  res.setHeader("Content-Transfer-Encoding", "binary");
			  res.setHeader("Content-Disposition", 
			  "attachment; filename= " + fileName + ".plist"); 
			  
			  BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		      Iterator<BlobInfo> iterator = null;
		      BlobInfo info = null;
		      iterator = new BlobInfoFactory().queryBlobInfos();
		  	
		      while(iterator.hasNext()){
			      	info = iterator.next();        	
			      	if(fileName.toString().equals(info.getFilename().toString())){
			      		blobstoreService.serve(info.getBlobKey(), res);
			      		break;
			      	}        	
		      }    
		      
		  } catch (Exception e) {
		   		res.getWriter().println(e.getMessage());
		  }
	 }


	 public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		 doGet(req, res);
	 }
}